package pub.tbc.rubbish.client.util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import pub.tbc.rubbish.client.Constant;
import pub.tbc.toolkit.PropsUtil;

/**
 * @author tbc on 2016/12/6 14:23:50.
 */
public class ZkHelper {
    private static final String DEFAULT_ZK_CONN = "127.0.0.1:2181";
    private static CuratorFramework zkClient = null;

    public static CuratorFramework getCuratorFrameworkWithOptions() {
        return getCuratorFrameworkWithOptions(
                new ExponentialBackoffRetry(1000, 3),
                1000,
                1000);
    }

    /**
     * 用可选参数获取一个客户端连接
     *
     * @param retryPolicy         重试策略
     * @param connectionTimeoutMs 连接超时时间
     * @param sessionTimeoutMs    会话过期时间
     * @return CuratorFramework
     */
    public static CuratorFramework getCuratorFrameworkWithOptions(
            RetryPolicy retryPolicy,
            int connectionTimeoutMs,
            int sessionTimeoutMs) {
        if (zkClient == null) {
            synchronized (ZkHelper.class) {
//                String connectionString = getZkConn();
                if (zkClient == null) {
                    zkClient = CuratorFrameworkFactory.builder()
                            .connectString(getZkConn())
                            .retryPolicy(retryPolicy)
                            .connectionTimeoutMs(connectionTimeoutMs)
                            .sessionTimeoutMs(sessionTimeoutMs)
                            .build();
                    //
                    zkClient.start();
                }
            }
        }
        return zkClient;
    }

    /**
     * 用默认参数获取一个简单客户端
     *
     * @return .
     */
    public static CuratorFramework getCuratorFrameworkSimple() {
        String connectionString = getZkConn();
        // 推荐的重试策略
        // these are reasonable arguments for the ExponentialBackoffRetry.
        // The first retry will wait 1 second - 第一次重试将等待1秒
        // the second will wait up to 2 seconds -
        // the third will wait up to 4 seconds.
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
        // The simplest way to get a CuratorFramework instance. This will use default values.
        // The only required arguments are the connection string and the retry policy
        return CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
    }

    private static String getZkConn() {
        return PropsUtil.getString(
                PropsUtil.load(Constant.DEFAULT_CONFIG_FILE),
                Constant.ZK_CONN,
                DEFAULT_ZK_CONN
        );
    }
}
